﻿using System;
using System.Collections.Generic;

namespace Flagwind.Externals.Redis.Commands
{
	[Flagwind.Services.CommandOption("all", Description = "${Text.DictionaryGetCommand.All}")]
	[Flagwind.Services.CommandOption("count", Type = typeof(int), DefaultValue = 25, Description = "${Text.DictionaryGetCommand.Count}")]
	[Flagwind.Services.CommandOption("pattern", Type = typeof(string), Description = "${Text.DictionaryGetCommand.Pattern}")]
	public class DictionaryGetCommand : RedisCommandBase
	{
		#region 构造方法

		public DictionaryGetCommand() : base("Get")
		{
		}

		public DictionaryGetCommand(IRedisService redis) : base(redis, "Get")
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(Services.CommandContext context)
		{
			if(context.Expression.Arguments.Length < 1)
				throw new Flagwind.Services.CommandException("Missing arguments.");

			var dictionary = this.Redis.GetDictionary(context.Expression.Arguments[0]);

			if(dictionary == null)
			{
				context.Error.WriteLine($"The '{context.Expression.Arguments[0]}' dictionary is not existed.");
				return null;
			}

			switch(context.Expression.Arguments.Length)
			{
				case 1:
					if(context.Expression.Options.Contains("all"))
					{
						foreach(var entry in dictionary)
							context.Output.WriteLine($"{entry.Key}={entry.Value}");
					}

					return dictionary;
				case 2:
					var result = dictionary[context.Expression.Arguments[1]];
					context.Output.WriteLine(result);
					return result;
			}

			var keys = new string[context.Expression.Arguments.Length - 1];
			Array.Copy(context.Expression.Arguments, 1, keys, 0, keys.Length);

			var values = dictionary.GetValues(keys);

			foreach(var value in values)
				context.Output.WriteLine(value);

			return values;
		}

		#endregion
	}
}